import os
import json
import re
import openpyxl
from datetime import datetime
from tkinter import messagebox
import tkinter as tk


# 定义 JSON 配置文件路径
config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.json')

# 初始化配置文件
def initialize_config():
    if not os.path.exists(config_file):
        with open(config_file, 'w') as f:
            json.dump({}, f)  # 创建一个空的 JSON 文件

def log_operation(message, log_text):
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_text.config(state=tk.NORMAL)
    log_text.insert(tk.END, f"[{current_time}] : {message}\n")
    log_text.config(state=tk.DISABLED)
    log_text.yview(tk.END)

    # 创建存储日志文件的文件夹
    log_directory = "logs"
    if not os.path.exists(log_directory):
        os.makedirs(log_directory)
    
    # 获取当前日期并创建文件夹
    date_str = datetime.now().strftime("%Y-%m-%d")
    folder_path = os.path.join(log_directory, date_str)
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    
    # 日志文件路径
    log_file_path = os.path.join(folder_path, "log.txt")
    # 写入日志文件
    with open(log_file_path, "a") as log_file:
        log_file.write(f"[{current_time}] : {message}\n")



def save_to_config(key, value, log_text, label_text):
    initialize_config()  # 确保配置文件存在
    
    # 检查 value 是否为空
    if not value:
        messagebox.showerror("错误", "保存的值不能为空！")
        return False  # 值为空，返回 False
    
    with open(config_file, 'r') as f:
        config_data = json.load(f)
    
    config_data[key] = value

    with open(config_file, 'w') as f:
        json.dump(config_data, f, indent=4)

    # 记录操作
    log_operation(f"保存了{label_text}: {value}", log_text)
    return True  # 写入成功，返回 True



# 从 JSON 文件读取数据
def read_from_config(key):
    initialize_config()  # 确保配置文件存在
    with open(config_file, 'r') as f:
        config_data = json.load(f)
        return config_data.get(key, "")  # 返回对应的值，如果不存在则返回空字符串

# IP 地址格式校验
def validate_ip_address(ip_address):
    ip_pattern = re.compile(r'^(\d{1,3}\.){3}\d{1,3}$')
    if ip_pattern.match(ip_address):
        parts = ip_address.split(".")
        return all(0 <= int(part) <= 255 for part in parts)
    return False

def find_password(sn_value):
    # 读取配置
    password_folder_path = read_from_config("password_folder_path")
    password_row = read_from_config("password_row")

    # 空值检查
    if not password_folder_path:
        messagebox.showwarning("警告", "密码文件夹路径为空！")
        return
    if not password_row:
        messagebox.showwarning("警告", "密码列名为空！")
        return

    # 遍历文件夹中的所有xlsx文件
    for filename in os.listdir(password_folder_path):
        if filename.endswith('.xlsx'):
            xlsx_file = os.path.join(password_folder_path, filename)
            try:
                workbook = openpyxl.load_workbook(xlsx_file, data_only=True)
                sheet = workbook.active

                # 获取密码行对应的列索引
                header = [cell.value for cell in sheet[1]]  # 假设第一行为标题行
                if password_row not in header:
                    messagebox.showwarning("警告", f"未找到列名 {password_row}！")
                    continue
                
                password_col_index = header.index(password_row)

                # 遍历行，查找sn_value
                for row in sheet.iter_rows(values_only=True):
                    if row and sn_value in row:
                        # 找到对应行，提取密码
                        password_value = row[password_col_index]  # 使用列索引提取值
                        if password_value:
                            print(f"密码", f"找到的密码: {password_value}")
                            return password_value
                        else:
                            messagebox.showwarning("警告", "找到的密码为空！")
                        return  # 找到后返回

            except Exception as e:
                messagebox.showerror("错误", f"读取文件 {filename} 时出错: {e}")

    messagebox.showinfo("信息", "未找到对应的sn_value。")



def create_input_with_button(right_frame, label_text, initial_insert_arg, y_position, log_text, config_key, validate_func=None):
    # 默认 x 值
    x_label = 100
    x_entry = 100
    x_button = x_entry + 10 + 500  # 假设输入框宽度为500

    # 创建标签
    label = tk.Label(right_frame, text=label_text, font=("Arial", 20), bg="white")
    label.place(x=x_label, y=y_position, width=500, height=30)

    # 创建输入框
    entry = tk.Entry(right_frame, font=("Arial", 15), width=50, borderwidth=2, relief="solid")
    entry.place(x=x_entry, y=y_position + 30, width=500, height=30)
    entry.insert(0, initial_insert_arg)

    # 保存按钮回调函数
    # 保存按钮回调函数
    def save():
        value = entry.get()
        if not value:  # 先进行空判断
            messagebox.showerror("错误", f"{label_text}不能为空！")
            return
        
        if validate_func and not validate_func(value):  # 如果提供了验证函数，且验证失败
            messagebox.showerror("错误", f"{label_text}格式不正确！")
            return
        
        save_to_config(config_key, value, log_text, label_text)

    # 创建保存按钮
    button = tk.Button(right_frame, text="保存", font=("Arial", 15), command=save)
    button.place(x=x_button, y=y_position + 30, width=80, height=30)


